<template>
  <el-dialog
    v-el-drag-dialog
    title="商品模式批量调价"
    :visible.sync="dialogVisible"
    width="80%"
    @close="reset"
  >
    <el-form ref="dataForm" class="form" :model="query" label-position="right" label-width="80px">
      <el-form-item label="商品分类" prop="gtName">
        <el-input v-model="query.gtName" disabled />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="query.goodsName" disabled />
      </el-form-item>

      <el-form-item label="关键字" class="merge-item">
        <el-select v-model="query.keyId" clearable @change="changeKeyId">
          <el-option v-for="(l,i) in keyWordsList" :key="i" :value="l.keyId" :label="l.keyName" />
        </el-select>
      </el-form-item>
      <el-form-item label="波动方式" prop="gtName">
        <el-input :value="getpriceTypeName(query.priceType)" disabled />
      </el-form-item>
      <el-form-item label="波动价格" prop="goodsName">
        <el-input :value="query.price" disabled />
      </el-form-item>

      <el-form-item label="生效机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: orgTreeData
          }"
          @node-click="selectOrgTreeChange"
        />
      </el-form-item>
      <el-form-item label="查询方式" class="merge-item">
        <el-select v-model="query.flag" @change="chengSearchMethod">
          <el-option value="-1" label="全部" />
          <el-option value="1" label="已生效" />
          <el-option value="2" label="未生效" />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 66%;" label="" label-width="0" class="merge-item">
        <p style="  color: red;">  全部：所有未过期的用户；生效中：当前时间在有效时间内(包含报价待审用户)；未生效：有效开始时间大于当前时间的用户</p>
      </el-form-item>

    </el-form>
    <div>
      <el-radio v-model="radio" label="1">选择本页</el-radio>
      <el-radio v-model="radio" label="2">选择全部客户</el-radio>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      style="margin-top: 15px;"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      height="300"
      highlight-current-row
      pagination
      :total="tableData.total"
      @row-click="clcikCurrentRow"
      @selection-change="selectionChange"
      @fetch="fetchData"
    />
    <div style="margin-top: 10px;">
      <!-- <span>本次调整</span> -->
      <el-form class="form" :model="query" label-position="right" label-width="80px">
        <el-form-item label="本次调整： 波动方式" label-width="150px" class="merge-item">
          <el-select v-model="submit.priceType">
            <el-option v-for="(l,i) in priceTypeMap" :key="i" :value="l.value" :label="l.desc" />
          </el-select>
        </el-form-item>
        <el-form-item label="波动价格" prop="goodsName">
          <el-input v-model="submit.price" />
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="reset">关闭</el-button>
      <el-button type="primary" @click="success">保存</el-button>
    </span>
  </el-dialog>

</template>

<script>
  import { CmsSpecialKeyWords, CmsSpecialAlldetail, CmsSpecialDeleteGoods, CmsSpecialUpdatePriceBatch } from '@/api'
  import { parseTime } from '@/utils'
  export default {
    name: 'allAdjust',
    props: ['orgTreeData', 'goodsTreeData'],
    data() {
      return {
        dialogVisible: false,
        keyWordsList: [],
        selectTableList: [],
        radio: '1',
        submit: { price: null, priceType: null },
        query: {
          keyId: -1
        },
        priceTypeMap: [{ 'value': 1, 'desc': '下浮', 'key': 'Fluctuating' }, { 'value': 2, 'desc': '固定', 'key': 'Fixed' }],
        tableData: {
          data: [],
          column: [
            { type: 'selection' },
            { label: '客户名称', prop: 'csmName', width: 120, align: 'center' },
            { label: '客户电话', prop: 'contactPhone', width: 100, align: 'center' },
            { label: '客户地址', prop: 'csmAddress', width: '', align: 'center' },
            { label: '客户编码', prop: 'csmCode', width: 80, align: 'center' },
            { label: '有效开始时间', prop: 'startDt', width: 150, align: 'center',
              render: (h, { row }) => <span>{row.startDt && parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}')}</span>
            },
            { label: '有效结束时间', prop: 'endDt', width: 150, align: 'center',
              render: (h, { row }) => <span>{row.endDt && parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}')}</span>
            },
            { label: '生效机构', prop: 'orgName', width: 150, align: 'center' },
            { label: '关键字', prop: 'keyName', width: 100, align: 'center' },
            { label: '操作', prop: 'op', width: 50, align: 'center',
              render: (h, { row, column, $index }) => <span onClick={() => { this.delShop(row, $index) }} style='color:red;cursor: pointer'>X</span>
            }
          ]
        }
      }
    },
    computed: {

    },
    watch: {
      'radio': {
        handler: function(val) {
          if (val === '1') {
            console.log(this.tableData.data.length <= 0)
            this.tableData.data.forEach(row => {
              this.$refs.lbTable.toggleRowSelection(row, true)
            })
          }
        },
        immediate: true
      }

    },
    async created() {

    },
    mounted() {
      // const vm = this
      // vm.$watch('radio', (val) => {
      //   console.log(val)
      //   if (val === '1') {
      //     this.tableData.data.forEach(row => {
      //       this.$refs.lbTable.toggleRowSelection(row, true)
      //     })
      //   }
      // }, { deep: true, immediate: true })
    },
    methods: {
      getpriceTypeName(val) {
        // console.log(this)
        var arr = this.$data.priceTypeMap.find(l => val === l.value)
        if (arr) {
          return arr.desc
        }
        return ''
      },
      async success() {
        console.log(this.$refs.lbTable)
        const params = {
          priceCategoryDetailInfo: { ...this.submit, 'goodsId': this.query.goodsId },
          priceWithCsmInfoList: this.selectTableList,
          prePriceWithCsmInfo: {}
        }
        if (this.radio === '2') {
          params.prePriceWithCsmInfo = { 'goodsId': this.query.goodsId, 'priceType': this.query.priceType, 'price': this.query.price, 'flag': this.query.flag, 'keyId': this.query.keyId }
        }
        if (!this.submit.price) {
          this.$message.error('请输入调整后的价格')
          return
        }
        const reg = /^(-?\d+)(\.\d+)?$/
        // console.log(reg.test(this.submit.price))
        if (!reg.test(this.submit.price)) {
          this.$message.error('波动价格输入有误,请输入数字或小数')
          return
        }
        if (!this.selectTableList.length) {
          this.$message.error('请勾选要调价的数据')
          return
        }
        console.log(params)
        const res = await CmsSpecialUpdatePriceBatch(params)
        if (res.success) {
          this.$message.success('保存成功')
        }
        this.reset()
        this.$emit('afterSave')
      },
      clcikCurrentRow(row) {
        this.$refs.lbTable.toggleRowSelection(row)
        // console.log(row)
      },
      // 监听查询方式改变
      chengSearchMethod() {
        this.fetchData({})
      },
      // 监听关键字方式改变
      changeKeyId() {
        this.fetchData({})
      },
      // 当前选中的表格行集合
      selectionChange(val) {
        this.selectTableList = val
        // console.log(val)
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        this.radio = 0
        const params = {
          // ...this.query,
          'goodsId': this.query.goodsId, 'priceType': this.query.priceType, 'price': this.query.price, 'flag': this.query.flag,
          'keyId': this.query.keyId, 'scopeOrgSNNo': this.query.orgSNNo,
          currentPage,
          pageSize
        }

        const res = await CmsSpecialAlldetail(params)
        this.tableData.data = res.data.rows
        // if (currentPage === 1) this.tableData.data.total = res.data.total
        setTimeout(() => {
          this.radio = '1'
        }, 0)
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      async open(row) {
        await this.getKeyWords()
        this.dialogVisible = true
        this.query = { ...row }
        this.query.orgSNNo = null
        this.query.keyId = 0
        this.query.flag = '-1'
        this.submit.priceType = this.query.priceType
        this.submit.price = this.query.price
        console.log(this.query)
        await this.fetchData({})
      },
      // 删除商品
      delShop(row) {
        const vm = this
        this.$confirm(`确定要删除吗？`, '提示', {
          type: 'info'
        }).then(() => {
          var params = {
            categoryDetailId: row.categoryDetailId,
            csmId: row.csmId,
            priceCgId: row.priceCgId
          }
          try {
            CmsSpecialDeleteGoods(params).then(data => {
              vm.fetchData({})
            })
          } catch (e) {
            console.log(e)
          }
        })
      },
      // 获取关键字
      async getKeyWords() {
        const params = {
          currentPage: 1,
          pageSize: 20
        }
        try {
          const res = await CmsSpecialKeyWords(params)
          this.keyWordsList = res.data.rows.filter(l => l.keyStatus !== -1)
          this.keyWordsList.unshift({ keyId: 0, keyName: '请选择' })
          console.log(res)
        } catch (e) {
          console.log(e)
        }
      },
      reset() {
        this.keyWordsList = []
        this.selectTableList = []
        this.radio = '1'
        this.submit = { price: null, priceType: null }
        this.query = {
          keyId: -1
        }
        this.tableData.data = []
        this.dialogVisible = false
        // this.parentFetchData({})
      },
      // 选择机构
      selectOrgTreeChange() {
        this.fetchData({})
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
</style>
